package lookas.screen;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import lookas.GoogleMaps;
import lookas.Position;

public class SaveScreen extends SimpleScreen implements Runnable {
	private Vector addr;
	private TextField file;

	public void setAddr(Vector addr) {
		this.addr = addr;
	}

	protected void init() {
		form = new Form("Save");
		String fName = "file:///E:/TrekBuddy/wpts/loc.gpx";
		file = new TextField("File name", fName, 128, TextField.PLAIN);
		form.append(file);
		Command ok = new Command("OK", Command.ITEM, 0);
		addCommand(ok, this);
	}

	public SaveScreen(Screen parent) {
		super(parent);
	}

	public void run() {
		form.append("Geopositioning...\n");
		Vector ads = new Vector();
		Enumeration els = addr.elements();
		GoogleMaps gMap = new GoogleMaps();
		while (els.hasMoreElements()) {
			TextField t = (TextField) (els.nextElement());
			String address = t.getString();
			Position pos;
			try {
				pos = gMap.geocodeAddress(address);
				ads.addElement(pos);
				form.append(pos.address + "... OK\n");
			} catch (Exception e) {
				form.append(address + " " + e.getMessage() + "\n");
			}
		}
		form.append("Saving...\n");
		if (saveFile(file.getString(), ads))
			form.append("Done.\n");
		else {
			form.deleteAll();
			form.append(file);
		}
	}

	private boolean saveFile(String name, Vector dane) {
		OutputStream ops = null;
		FileConnection fconn = null;
		try {
			fconn = (FileConnection) Connector.open(name, Connector.READ_WRITE);
			if (fconn.exists()) {
				new WarnScreen(this, "file exists");
				return false;
			}
			fconn.create();
			ops = fconn.openOutputStream();
			ops.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<gpx>\n"
					.getBytes());
			Enumeration els = dane.elements();
			while (els.hasMoreElements()) {
				Object obj = els.nextElement();
				Position pos = (Position) obj;
				String s = "<wpt lat=\"" + pos.lat + "\" lon=\"" + pos.lon
						+ "\"><name>" + pos.address + "</name></wpt>\n";
				ops.write(s.getBytes());
			}
			ops.write("</gpx>".getBytes());
		} catch (IOException e) {
			new WarnScreen(this, e.getMessage());
			return false;
		} catch (SecurityException e) {
			new WarnScreen(this, e.getMessage());
			return false;
		} finally {
			try {
				ops.close();
				fconn.close();
			} catch (Exception e) {
			}
		}
		return true;
	}

	public Displayable getForm() {
		return form;
	}
}
